import java.util.ArrayList;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Studentsreader {
	
	// reads specified file, returns a Classroom following the csv format
	public Classroom read(String file) throws IllegalCSVStructureException {
		// some variables
		boolean header = true;
		int optsubcount = 0;
		String[] optsubjects = null;
		ArrayList<Student> students = new ArrayList<Student>();
		
		// file io
		try (BufferedReader br = new BufferedReader(new FileReader(file))) {
			for (String line; (line = br.readLine()) != null;) {
				// if we're currently at the header of our csv file, which *should*
				// be true for the first line of every csv file ever
				if (header) {
					header = false;
					String[] splitheader = line.split(";");
					// keep count of optional subjects
					// 3 positional fields are always required, nr, lastname and surname
					optsubcount = splitheader.length - 3;
					// check for invalidity of file
					if (optsubcount < 0)
						throw new IllegalCSVStructureException("source CSV is missing the minimum required fields");
					
					optsubjects = new String[optsubcount];
					// for optsubjects
					for (int i = 0; i < optsubcount; i++) {
						optsubjects[i] = splitheader[i + 3];
					}
				} else {
					// if line is anything that isn't the header
					String[] splitline = line.split(";", -1);
					// hardcoded required fields
					String nr = null, lastname = null, surname = null;
					// optional subjects
					Boolean[] visitsoptsubs = new Boolean[optsubcount];
					// iterate line contents
					for (int i = 0; i < optsubcount + 3; i++) {
						switch (i) {
							case 0:
								nr = splitline[i];
								continue;
							case 1:
								lastname = splitline[i];
								continue;
							case 2:
								surname = splitline[i];
								continue;
							default:
								if (!"".equals(splitline[i]))
									visitsoptsubs[i - 3] = true;
								else
									visitsoptsubs[i - 3] = false;
								continue;
						}
					}
					students.add(new Student(nr, lastname, surname, visitsoptsubs));
				}
			}
		} catch (IOException e) {
			// stuff happened I guess
		}
		
		// create and populate classroom
		Classroom classroom = new Classroom(students.toArray(new Student[students.size()]), optsubjects);
		
		return classroom;
	}
}